package com.aishua.fire.controller;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.http.util.TextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import com.aishua.fire.common.CookieUtils;
import com.aishua.fire.common.JsonObjectResult;
import com.aishua.fire.common.anno.ModuleService;
import com.aishua.fire.common.anno.PermMapping;
import com.aishua.fire.common.constant.BigMenuConstants;
import com.aishua.fire.common.constant.ModuleConstants;
import com.aishua.fire.entity.account.GraphicCode;
import com.aishua.fire.entity.account.Session;
import com.aishua.fire.entity.login.AppLoginRespInfo;
import com.aishua.fire.entity.login.UserLoginInfo;
import com.aishua.fire.jpa.entity.Account;
import com.aishua.fire.service.LoginService;
import com.aishua.fire.service.OrganizationService;
import com.google.code.kaptcha.impl.DefaultKaptcha;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Api(value = "登录操作相关",tags = {"登录操作相关接口"})
@Controller
public class LoginController {

	@Autowired  
	private DefaultKaptcha defaultKaptcha;
	
	@Autowired
	private LoginService loginService;
	
	@Autowired
	private OrganizationService organizationService;
	
	@SuppressWarnings("rawtypes")
	@PermMapping(noValidate=true)
	@ApiOperation(value = "登录验证接口")
	@PostMapping(value = { "/login" })
	public ResponseEntity<JsonObjectResult> login(HttpServletRequest request, HttpSession session,
			HttpServletResponse resp, @RequestBody UserLoginInfo loginInfo) {
		Account user =new Account();
		if (TextUtils.isBlank(loginInfo.getUserPwd()) || TextUtils.isBlank(loginInfo.getUserName())) {
			String msg = "账户密码不能为空";
			JsonObjectResult r = JsonObjectResult.makeErrorResult(msg);
			return ResponseEntity.ok(r);
		}
		String id = UUID.randomUUID().toString().replace("-", "");
		log.info("登录接口请求验证码为:{}", loginInfo.getValidateCode());
		// 根据uuid查询验证码  (z暂时屏蔽验证码)
		GraphicCode code = loginService.getCode(loginInfo.getUuid(), loginInfo.getValidateCode().toUpperCase());
		user = loginService.authenticateLogin(loginInfo.getUserName(), loginInfo.getUserPwd());
		//  (z暂时屏蔽验证码)
		if (code == null || user == null) {

			String msg = "账号密码错误,或验证码错误";
			JsonObjectResult r = JsonObjectResult.makeErrorResult(msg);
			return ResponseEntity.ok(r);
		}
		long time = session.getMaxInactiveInterval() * 2000 + System.currentTimeMillis();
		Date expiredDate = new Date(time);
		loginService.updateSessionInfo(id, user.getLoginId(), expiredDate);
		//更新登陆时间
		loginService.updateloginTime(user.getLoginId());
		Cookie  cookie = new Cookie("sessionId", id);
		cookie.setPath("/");
		cookie.setMaxAge(3600);
		resp.addCookie(cookie);
		 Map<String,String> m = new HashMap<String,String>();
	    m.put("sessionId", id);
		JsonObjectResult r = JsonObjectResult.makeSuccessResult(m);
		return ResponseEntity.ok(r);
	}
	
	@SuppressWarnings("rawtypes")
	@PermMapping(noValidate=true)
	@ApiOperation(value = "app端登录验证接口")
	@PostMapping(value = { "/appLogin" })
	public ResponseEntity<JsonObjectResult> appLogin(HttpServletRequest request, HttpSession session,
			HttpServletResponse resp, @RequestBody UserLoginInfo loginInfo) {
		Account user =new Account();
		AppLoginRespInfo respInfo =new AppLoginRespInfo();
		if (TextUtils.isBlank(loginInfo.getUserPwd()) || TextUtils.isBlank(loginInfo.getUserName())) {
			String msg = "账户密码不能为空";
			JsonObjectResult r = JsonObjectResult.makeErrorResult(msg);
			return ResponseEntity.ok(r);
		}
		String id = UUID.randomUUID().toString().replace("-", "");
		user = loginService.authenticateAppLogin(loginInfo.getUserName(), loginInfo.getUserPwd());
		if (user == null) {
			String msg = "账号密码错误,或验证码错误";
			JsonObjectResult r = JsonObjectResult.makeErrorResult(msg);
			return ResponseEntity.ok(r);
		}
		//更新appsessionId
		loginService.updateAppSessionInfo(id, user.getLoginId());
		//更新登陆时间
		loginService.updateloginTime(user.getLoginId());
		//根据id查询对应信息
		respInfo =loginService.getUserInfo(user.getLoginId());
		respInfo.setAppSession(id);
		Cookie  cookie = new Cookie("sessionId", id);
		cookie.setPath("/");
		resp.addCookie(cookie);
		 Map<String,String> m = new HashMap<String,String>();
	    m.put("appSession", id);
		JsonObjectResult r = JsonObjectResult.makeSuccessResult(respInfo);
		return ResponseEntity.ok(r);
	}
	
	
	
	@ApiOperation(value="获取登录验证码图片接口")
    @GetMapping(value = {"/getLoginCode"} )
	public void getLoginCode(HttpServletRequest httpServletRequest,
			HttpServletResponse httpServletResponse, HttpSession session, String uuid) throws IOException {
		byte[] captchaChallengeAsJpeg = null;
		ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
		try {

			String createText = defaultKaptcha.createText();
			log.info("登录获取图片接口返回的验证码是:{}", createText);
			loginService.saveCode(uuid, createText);
			// 使用生成的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
			BufferedImage challenge = defaultKaptcha.createImage(createText);
			ImageIO.write(challenge, "jpg", jpegOutputStream);
		} catch (IllegalArgumentException e) {
			 httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);  
			 return;
		}
		// 定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
		captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
		httpServletResponse.setHeader("Cache-Control", "no-store");
		httpServletResponse.setHeader("Pragma", "no-cache");

		httpServletResponse.setDateHeader("Expires", 0);
		httpServletResponse.setContentType("image/jpeg");
		ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
		responseOutputStream.write(captchaChallengeAsJpeg);
		responseOutputStream.flush();
		responseOutputStream.close();
	}
	
	/**
	 * 修改密碼接口
	 * @param session
	 */
	@PermMapping(onlyLogin = true)
	@ModuleService(totalModule=BigMenuConstants.systemManager,moduleName=ModuleConstants.systemAccount)
	@ApiOperation(value="修改_当前账户密码接口")
	@GetMapping(value = {"/updatePwd/{newPwd}"} )
	public void updatePwd(@PathVariable("newPwd") String newPwd) {
		loginService.updatePwd(newPwd);
    }
	
	
	@SuppressWarnings("rawtypes")
	@ModuleService(totalModule=BigMenuConstants.systemManager,moduleName=ModuleConstants.systemAccount)
	@ApiOperation(value="获取当前账号id接口")
	@GetMapping(value = {"/getUserid"} )
	public ResponseEntity<JsonObjectResult> getUserId(ServletRequest servletRequest) {
		HttpServletRequest req = (HttpServletRequest) servletRequest;
		String sessionId = CookieUtils.getCookie(req, "sessionId");
		//根据sessionId获取当前账号id
		Session s = loginService.findBySessionId(sessionId);
		JsonObjectResult r = JsonObjectResult.makeSuccessResult(s.getUser_id());
		return ResponseEntity.ok(r);
    }
	
	@SuppressWarnings("rawtypes")
	@ApiOperation(value = "退出登录")
	@GetMapping(value = { "/exit" })
	public ResponseEntity<JsonObjectResult> exit(ServletRequest servletRequest) {
		HttpServletRequest req = (HttpServletRequest) servletRequest;
		String sessionId = CookieUtils.getCookie(req, "sessionId");
		loginService.delSessionInfo(sessionId);
		JsonObjectResult r = JsonObjectResult.makeSuccessResult(null);
		return ResponseEntity.ok(r);
	}
	
	
	/***
	 * 根据当前账号查看所属角色id
	 * @param servletRequest
	 * @return
	 */
	public String getr_idWitha_id(ServletRequest servletRequest){
		//查询当前登录账号信息
		HttpServletRequest req = (HttpServletRequest) servletRequest;
		String sessionId = CookieUtils.getCookie(req, "sessionId");
		//根据sessionId获取当前账号id
		Session s = loginService.findBySessionId(sessionId);
		log.info("当前登录账号id:{}", s.getUser_id());
		//根据账号id查询角色id
		
		return s.getUser_id()+"";
	}
	
	
}
